package com.fbt.transfer.app.driver.util;

import android.Manifest;
import android.app.Activity;
import android.app.Application;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationCompat;
import androidx.core.content.ContextCompat;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.json.JSONUtil;
import com.fbt.transfer.app.driver.activity.MainActivity;
import com.fbt.transfer.app.driver.model.OrderTypeEnum;
import com.fbt.transfer.app.driver.model.SocketMessage;
import com.fbt.transfer.app.driver.model.ValueDesc;
import com.fbt.transfer.app.driver.R;
import com.fbt.transfer.app.driver.model.BsType;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author tuocoo
 */
public class NotificationUtils {

  private static final String TAG = "NotificationUtils";
  private static final String CHANNEL_ID = "transfer_dispatch_channel";
  private static final String CHANNEL_NAME = "调度通知";
  private static final String CHANNEL_DESCRIPTION = "接收调度系统的重要通知";
  private static int NOTIFICATION_ID = 1001;

  private static NotificationManager notificationManager;
  private static final List<WeakReference<Activity>> CURRENT_ACTIVITIES = new ArrayList<>();

  public static final Application.ActivityLifecycleCallbacks ACTIVITY_LIFECYCLE_CALLBACKS =
      new Application.ActivityLifecycleCallbacks() {
        @Override
        public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
          addActivity(activity);
        }

        @Override
        public void onActivityStarted(Activity activity) {
          addActivity(activity);
        }

        @Override
        public void onActivityResumed(Activity activity) {
          addActivity(activity);
        }

        @Override
        public void onActivityPaused(Activity activity) {
          // No-op
        }

        @Override
        public void onActivityStopped(Activity activity) {
          // No-op
        }

        @Override
        public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
          // No-op
        }

        @Override
        public void onActivityDestroyed(Activity activity) {
          removeActivity(activity);
        }
      };

  private static void addActivity(Activity activity) {
    synchronized (CURRENT_ACTIVITIES) {
      // Remove any existing weak references to this activity
      CURRENT_ACTIVITIES.removeIf(ref -> ref.get() == activity);
      // Add new weak reference
      CURRENT_ACTIVITIES.add(new WeakReference<>(activity));
      LogUtils.d(TAG, "Added activity: " + activity.getClass().getSimpleName());
    }
  }

  private static void removeActivity(Activity activity) {
    synchronized (CURRENT_ACTIVITIES) {
      CURRENT_ACTIVITIES.removeIf(ref -> ref.get() == activity);
      LogUtils.d(TAG, "Removed activity: " + activity.getClass().getSimpleName());
    }
  }

  private static Activity getTopActivity() {
    synchronized (CURRENT_ACTIVITIES) {
      for (int i = CURRENT_ACTIVITIES.size() - 1; i >= 0; i--) {
        WeakReference<Activity> ref = CURRENT_ACTIVITIES.get(i);
        Activity activity = ref.get();
        if (activity != null && !activity.isFinishing()) {
          LogUtils.d(TAG, "Found top activity: " + activity.getClass().getSimpleName());
          return activity;
        } else {
          CURRENT_ACTIVITIES.remove(i);
          LogUtils.d(TAG, "Removed invalid activity reference");
        }
      }
    }
    LogUtils.e(TAG, "No valid top activity found");
    return null;
  }

  public static synchronized void init(Context context) {
    if (notificationManager == null) {
      notificationManager =
          (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
      createNotificationChannel(context);
    }
    // 注册Activity生命周期回调
    ((Application) context.getApplicationContext())
        .registerActivityLifecycleCallbacks(ACTIVITY_LIFECYCLE_CALLBACKS);
  }

  public static synchronized void release(Context context) {
    if (notificationManager != null) {
      ((Application) context.getApplicationContext())
          .unregisterActivityLifecycleCallbacks(ACTIVITY_LIFECYCLE_CALLBACKS);
      notificationManager = null;
    }
  }

  private static void createNotificationChannel(Context context) {
    NotificationChannel channel =
        new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
    channel.setDescription(CHANNEL_DESCRIPTION);
    channel.enableVibration(true);
    channel.enableLights(true);
    channel.setLightColor(ContextCompat.getColor(context, R.color.colorPrimary));
    notificationManager.createNotificationChannel(channel);
  }

  public static void showNotification(Context context, String messageBody) {
    if (notificationManager == null) {
      init(context);
    }
    // 检查通知权限
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
      if (ActivityCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS)
          != PackageManager.PERMISSION_GRANTED) {
        LogUtils.e(TAG, "通知权限未授予");
        return;
      }
    }
    if (JSONUtil.isTypeJSONObject(messageBody)) {
      SocketMessage socketMessage = JsonUtil.toBean(messageBody, SocketMessage.class);
      if (socketMessage == null) {
        return;
      }
      // 构建通知
      String title = socketMessage.getTitle();
      if (CharSequenceUtil.isNotEmpty(title)) {
        // 创建点击通知时打开的Intent
        Intent intent = new Intent(context, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent =
            PendingIntent.getActivity(
                context,
                0,
                intent,
                PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
            );
        NotificationCompat.Builder builder =
            new NotificationCompat.Builder(context, CHANNEL_ID)
                .setSmallIcon(R.drawable.ic_notification)
                .setContentTitle(title)
                .setContentText(CharSequenceUtil.trimToEmpty(socketMessage.getTextMsg()))
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setAutoCancel(true)
                .setVibrate(new long[]{0, 500, 200, 500})
                .setLights(ContextCompat.getColor(context, R.color.colorPrimary), 1000, 1000)
                .setContentIntent(pendingIntent);
        notificationManager.notify(NOTIFICATION_ID++, builder.build());
        // 发送通知
        Optional.ofNullable(socketMessage.getBusinessType())
            .ifPresent(
                businessType -> {
                  // 播放语音提示
                  try {
                    playAudio(context, businessType, socketMessage);
                  } catch (Exception e) {
                    LogUtils.e(TAG, "播放语音异常", e);
                  }
                  // 使用当前活动的上下文显示对话框
                  Activity currentActivity = getTopActivity();
                  if (currentActivity != null) {
                    LogUtils.d(
                        TAG,
                        "Showing dialog in activity: "
                            + currentActivity.getClass().getSimpleName()
                    );
                    currentActivity.runOnUiThread(
                        () -> {
                          try {
                            //OrderCardDialog.showWithCustomText(currentActivity, socketMessage);
                          } catch (Exception e) {
                            LogUtils.e(TAG, "Error showing dialog: " + e.getMessage());
                          }
                        });
                  } else {
                    LogUtils.e(TAG, "当前活动上下文为空，无法显示对话框");
                  }
                });
      }
    } else {
      // 创建点击通知时打开的Intent
      Intent intent = new Intent(context, MainActivity.class);
      intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
      PendingIntent pendingIntent =
          PendingIntent.getActivity(
              context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
      NotificationCompat.Builder builder =
          new NotificationCompat.Builder(context, CHANNEL_ID)
              .setSmallIcon(R.drawable.ic_notification)
              .setContentTitle("平台消息")
              .setContentText(CharSequenceUtil.trimToEmpty(messageBody))
              .setPriority(NotificationCompat.PRIORITY_HIGH)
              .setAutoCancel(true)
              .setVibrate(new long[]{0, 500, 200, 500})
              .setLights(ContextCompat.getColor(context, R.color.colorPrimary), 1000, 1000)
              .setContentIntent(pendingIntent);
      notificationManager.notify(NOTIFICATION_ID++, builder.build());
      // 使用当前活动的上下文显示对话框
      Activity currentActivity = getTopActivity();
      if (currentActivity != null) {
        LogUtils.d(
            TAG, "Showing dialog in activity: " + currentActivity.getClass().getSimpleName());
        currentActivity.runOnUiThread(
            () -> {
              try {
               // SoundPlayUtil.playSound(context, R.raw.message_notice);
               // OrderCardDialog.showWithCustomText(currentActivity, "平台消息通知", messageBody);
              } catch (Exception e) {
                LogUtils.e(TAG, "Error showing dialog: " + e.getMessage());
              }
            });
      } else {
        LogUtils.e(TAG, "当前活动上下文为空，无法显示对话框");
      }
    }
  }

  private static void playAudio(Context context, ValueDesc businessType, SocketMessage socketMessage) {
    SocketMessage.RelateOrder orderInfo = socketMessage.getOrderInfo();
    BsType bsType = businessType.convertBsType();
    OrderTypeEnum orderType = orderInfo != null && orderInfo.getOrderType() != null
        ? orderInfo.getOrderType().convertOrderType() : null;
    if (BsType.PUSH_NEW_ORDER == bsType) {
      SoundPlayUtil.playSound(
          context,
          OrderTypeEnum.DROP_OFF == orderType
              ? R.raw.drop_off_new_order
              : R.raw.pick_up_new_order
      );
    } else if (BsType.PUSH_ORDER_REMIND == bsType) {
      SoundPlayUtil.playSound(
          context, OrderTypeEnum.DROP_OFF == orderType
              ? R.raw.drop_off_assgin : R.raw.pick_up_assign
      );
    } else if (BsType.BAD_COMMENT == bsType) {
      SoundPlayUtil.playSound(context, R.raw.bad_comment_notice
      );
    } else if (BsType.PUSH_ORDER_CANCEL == bsType) {
      SoundPlayUtil.playSound(
          context,
          OrderTypeEnum.DROP_OFF == orderType
              ? R.raw.drop_off_canceled
              : R.raw.pick_up_canceled
      );
    } else if (BsType.PUSH_ORDER_ASSIGN_RESULT == bsType) {
      SoundPlayUtil.playSound(
          context,
          Boolean.FALSE.equals(socketMessage.getAssignResult()) ||
              socketMessage.getOrderText().contains("拒绝")
              ? R.raw.reject_assign
              : R.raw.accpt_assign
      );
    } else {
      SoundPlayUtil.playSound(context, R.raw.message_notice);
    }
  }
}
